package com.shopping.cart.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.shopping.cart.feign.ProductFeignService;
import com.shopping.cart.interpretor.CartInterceptor;
import com.shopping.cart.service.CartService;
import com.shopping.cart.vo.CartItemVo;
import com.shopping.cart.vo.CartVo;
import com.shopping.cart.vo.SkuInfoVo;
import com.shopping.cart.vo.UserInfoVo;
import com.shopping.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CartServiceImpl implements CartService {

    private final String CART_PREFIX = "shopping:cart:";

    @Resource(name = "stringRedisTemplate")
    StringRedisTemplate redisTemplate;

    @Resource
    ProductFeignService productFeignService;

    @Resource
    ThreadPoolExecutor executor;

    /**
     * 添加到购物车
     *
     * @param skuId
     * @param num
     * @return
     */
    @Override
    public CartItemVo addToCart(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String res = (String) cartOps.get(skuId.toString());
        CartItemVo cartItemVo;
        // 购物车里没有该商品
        if (StringUtils.isEmpty(res)) {
            cartItemVo = new CartItemVo();
            // 1.远程调用当前要添加的商品信息
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                R skuInfo = productFeignService.getSkuInfo(skuId);
                SkuInfoVo data = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });

                cartItemVo.setIsChecked(true);
                cartItemVo.setCount(num);
                cartItemVo.setImage(data.getSkuDefaultImg());
                cartItemVo.setTitle(data.getSkuTitle());
                cartItemVo.setSkuId(data.getSkuId());
                cartItemVo.setPrice(data.getPrice());

            }, executor);

            // 2.远程查询sku的组合信息
            CompletableFuture<Void> getSkuSaleAttrValues = CompletableFuture.runAsync(() -> {
                List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
                cartItemVo.setSkuAttrs(skuSaleAttrValues);
            }, executor);

            try {
                // 3.异步查询结束后才能转换
                CompletableFuture.allOf(getSkuSaleAttrValues, getSkuInfoTask).get();
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        } else {
            // 购物车里有该商品就修改数量
            cartItemVo = JSONObject.parseObject(res, CartItemVo.class);
            cartItemVo.setCount(cartItemVo.getCount() + num);
        }
        String jsonString = JSONObject.toJSONString(cartItemVo);
        cartOps.put(skuId.toString(), jsonString);


        return cartItemVo;
    }

    /**
     * 获得购物车中的某个商品
     *
     * @param skuId
     * @return
     */
    @Override
    public CartItemVo getCartItem(Long skuId) {
        String s = (String) getCartOps().get(skuId.toString());
        return JSONObject.parseObject(s, CartItemVo.class);
    }

    @Override
    public CartVo getCart() {
        UserInfoVo userInfoVo = CartInterceptor.THREAD_LOCAL.get();

        CartVo cartVo = new CartVo();
        if (userInfoVo.getUserId() != null) {
            // 登录
            String cartKey = CART_PREFIX + userInfoVo.getUserId();
            // 如果临时购物车的数据还没有合并
            String tempCartKey = CART_PREFIX + userInfoVo.getUserKey();
            List<CartItemVo> tempCartItems = getCartItems(tempCartKey);
            if (!CollectionUtils.isEmpty(tempCartItems)) {
                // 临时购物车有数据,需要合并
                for (CartItemVo itemVo : tempCartItems) {
                    addToCart(itemVo.getSkuId(), itemVo.getCount());
                }
            }
            clearCart(tempCartKey);

            // 获得登录后的购物车数据
            List<CartItemVo> cartItems = getCartItems(cartKey);
            cartVo.setItems(cartItems);

        } else {
            // 未登录
            String cartKey = CART_PREFIX + userInfoVo.getUserKey();
            // 获得临时购物车的所有购物项
            List<CartItemVo> cartItems = getCartItems(cartKey);
            cartVo.setItems(cartItems);
        }

        return cartVo;
    }

    /**
     * 获取到我们要操作的购物车
     *
     * @return BoundHashOperations<String, Object, Object>
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoVo userInfoVo = CartInterceptor.THREAD_LOCAL.get();

        String cartKey;
        if (userInfoVo.getUserId() != null) {
            cartKey = CART_PREFIX + userInfoVo.getUserId();
        } else {
            cartKey = CART_PREFIX + userInfoVo.getUserKey();
        }

        return redisTemplate.boundHashOps(cartKey);
    }

    private List<CartItemVo> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();
        if (!CollectionUtils.isEmpty(values)) {
            return values.stream().map(obj -> {
                String str = (String) obj;
                return JSONObject.parseObject(str, CartItemVo.class);
            }).collect(Collectors.toList());

        }
        return null;
    }

    /**
     * 情况购物车
     *
     * @param cartKey
     */
    @Override
    public void clearCart(String cartKey) {
        redisTemplate.delete(cartKey);
    }
}
